package com.julyup.core.util;

import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象类处理工具
 *
 * @Author: zhenzhong.wang
 * @Date: 9/10/2018 12:59 PM
 */
public class ObjectUtils {

    /**
     * 对象转换为字节
     *
     * @param obj
     * @return
     */
    public static byte[] objectToByte(Object obj) {
        Assert.notNull(obj, "transform object can not be null !");
        byte[] bytes = null;
        try {
            // object to byte array
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);

            bytes = bo.toByteArray();

            bo.close();
            oo.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 字节转换为对象
     *
     * @param bytes
     * @return
     */
    public static Object byteToObject(byte[] bytes) {
        Assert.notNull(bytes, "transform byte array can not be null !");
        Object obj = null;
        try {
            // bytearray to object
            ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
            ObjectInputStream oi = new ObjectInputStream(bi);

            obj = oi.readObject();
            bi.close();
            oi.close();
        } catch (Exception e) {
            System.out.println("translation" + e.getMessage());
            e.printStackTrace();
        }
        return obj;
    }
}
